package com.violet.socket;

import org.springframework.web.socket.BinaryMessage;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.AbstractWebSocketHandler;

import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

public class OrderMessageSocket extends AbstractWebSocketHandler {

    private final List<WebSocketSession> sessions = new CopyOnWriteArrayList<>();

    // 前端推送的消息【文本数据】
    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        super.handleTextMessage(session, message);
    }

    // 前端推送的消息【二进制数据】
    @Override
    protected void handleBinaryMessage(WebSocketSession session, BinaryMessage message) throws Exception {
        super.handleBinaryMessage(session, message);
    }

    // 链接成功执行
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        System.out.println("链接成功：" + session);
        sessions.add(session);
    }

    // 链接关闭执行
    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        System.out.println("链接断开：" + session);
        sessions.remove(session);
    }

    // 消息推送
    public void sendMessage(String message) {
        for (WebSocketSession session : sessions) {
            try {

                session.sendMessage(new TextMessage(message));

            } catch (Exception e) {e.printStackTrace();}
        }
    }
}
